package com.matrix.async.core;

import java.util.Map;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.matrix.core.tools.WebUtil;

@Component
public class ExtendWebUtil{
	
	
	/**
	 * 同步方法注册bean到ApplicationContext中
	 * 
	 * @param beanName
	 * @param clazz
	 * @param original bean的属性值
	 */
	public static  void setBean(String beanName, Class<?> clazz,Map<String,Object> original) {
		ApplicationContext applicationContext = WebUtil.getApplicationContext();

		DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
		if(beanFactory.containsBean(beanName)){
			return;
		}
		//BeanDefinition beanDefinition = new RootBeanDefinition(clazz);
		GenericBeanDefinition definition = new GenericBeanDefinition();
		//类class
		definition.setBeanClass(clazz);
		//属性赋值
		definition.setPropertyValues(new MutablePropertyValues(original));
		//注册到spring上下文
		beanFactory.registerBeanDefinition(beanName, definition);
	}
	
	/**
	 * 删除spring中管理的bean
	 * @param beanName
	 */
	public static void removeBean(String beanName){
		ApplicationContext ctx = WebUtil.getApplicationContext();
		DefaultListableBeanFactory acf = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
		if(acf.containsBean(beanName)) {
		    acf.removeBeanDefinition(beanName);
		}
	}

}
